//
//  RHMePolicySetVC.m
//  RuiHeApp
//
//  Created by Yan Chen on 2025/1/21.
//

#import "RHMePolicySetVC.h"
#import "RHMePolicySystemTimeCell.h"
#import "RHMePolicyTimeRangeCell.h"
#import "RHMePolicyModel.h"
#import "SYChartTool.h"
#import "ZYSwitch.h"
#import "SettingOptionController.h"
#import "RHDeviceModel.h"
#import "RHEndPointModel.h"
#import "PasswordVerifyController.h"
#import "RHTools.h"
#import "RHMePolicyEditTimeVC.h"
#import "WSDatePickerView.h"
#import "NetworkAgent.h"
#import "RHMePolicyAddTipsView.h"
#import "RHMePolicyPatternVC.h"
#import "RHPatternModel.h"

@interface RHMePolicySetVC ()<UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate>

@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic ,strong) NSArray *dataArr;

@property (nonatomic ,strong) NSMutableArray *paraSectionArr;//每组的参数

@property (nonatomic ,assign) NSInteger paraIndex;//参数下标

@property (nonatomic, strong) NSArray *syncArr;//要同步的设备   deviceId

@property (nonatomic, strong) MBProgressHUD *hud;

@property (nonatomic ,assign) NSInteger timeIndex;//选择的时间段

@property (nonatomic ,strong) NSArray *timeArr;//对应的6个时间段

@property (nonatomic ,strong) UIView *timeView;

@property (nonatomic ,strong) QMUITextField *textField;//策略数量
@end

@implementation RHMePolicySetVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"策略配置".rh_localized;
    self.paraSectionArr = [NSMutableArray array];
    [self setupUI];
    self.timeIndex = 0;
    [self getPlantPolicyConfig];
}



- (void)setupUI{
    kWeakSelf;
    
    NSArray *arr = [SYChartTool loadJsonFileWithName:@"me_policy_config"];
    self.dataArr = [NSArray yy_modelArrayWithClass:[RHMePolicyModel class] json:arr];
    
    //生成默认6个时间段策略
    [self createPolicyModelWithCount:4 pattern:nil];

        
    UIBarButtonItem *rightItem = [UIBarButtonItem itemWithTitle:@"使用模板".rh_localized titleColor:CMainColorGreen titleFont:kSYSTEMFONT(14) Target:self Seletor:@selector(patternAction)];
    self.navigationItem.rightBarButtonItem = rightItem;

    
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [_tableView setBackgroundColor:kCOLOR_HEX(@"#F0F5FF")];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setSeparatorColor:UIColor.clearColor];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [_tableView registerClass:[RHMePolicySystemTimeCell class] forCellReuseIdentifier:@"RHMePolicySystemTimeCell"];
   
    [_tableView registerClass:[RHMePolicyTimeRangeCell class] forCellReuseIdentifier:@"RHMePolicyTimeRangeCell"];
    _tableView.tableHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 8)];
    _tableView.tableFooterView = [self footerView];
    [self.view addSubview:_tableView];
   
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.bottom.mas_offset(0);
        make.top.mas_offset(0);
    }];
    
}

-(void)getPlantPolicyConfig
{
    NSString *url = [NSString stringWithFormat:@"%@/%ld",H_getPlantPolicy,self.plantId];
    [RHPatternModel startGetWithCompletionAPIKey:url argument:@{} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if (resultModel.code == 200) {
            RHPatternModel *patternModel = resultModel.data;
            [self createPolicyModelWithCount:patternModel.segmentNum pattern:patternModel];
            [self.tableView reloadData];
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
}

#pragma mark ------ 创建相应个数的策略
-(void)createPolicyModelWithCount:(NSInteger)policyCount pattern:(RHPatternModel*)patternModel
{
    if (policyCount == 0) {
        return;
    }
    //保留系统时间设置
    RHMePolicyModel *systemTimeSectionModel = [self.dataArr firstObject];
    NSArray *arr = [SYChartTool loadJsonFileWithName:@"me_policy_config"];
    //替换时间段设置
    RHMePolicyModel *timeSectionModel = [[NSArray yy_modelArrayWithClass:[RHMePolicyModel class] json:arr] lastObject];
    self.dataArr = @[systemTimeSectionModel,timeSectionModel];
    
    NSArray *jsonDataArr;
    if (patternModel) {
        jsonDataArr = [patternModel.configJson jsonStringToArray];
    }
    NSMutableArray *rowArr = [NSMutableArray array];
    [self.dataArr enumerateObjectsUsingBlock:^(RHMePolicyModel*  _Nonnull sectionModel, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([sectionModel.type isEqualToString:@"time"]) {
            RHMePolicyModel *rowModel = [sectionModel.rows firstObject];
            RHMePolicyModel *chgTagModel = [rowModel.items safeObjectAtIndex:0];
            RHMePolicyModel *socModel = [rowModel.items safeObjectAtIndex:1];
            RHMePolicyModel *powerModel = [rowModel.items safeObjectAtIndex:2];
            //要拆分成几个时间段
            NSInteger timeRangeCount = 24 / policyCount;
            
            for (int i = 0; i <policyCount; i++) {
                //取出保存的参数
                NSDictionary *paraDic = [jsonDataArr safeObjectAtIndex:i];
                NSInteger start_hour = i==0? 0 : i * timeRangeCount ;
                NSInteger start_minute = 0;
                
                NSInteger end_hour = (i+1) * timeRangeCount;
                NSInteger end_minute = 0 ;
                if (end_hour == 24) {
                    end_hour = 0;
                }
                
                RHMePolicyModel *rowNewModel = [[RHMePolicyModel alloc]init];
                rowNewModel.type = rowModel.type;
                rowNewModel.comment = [NSString stringWithFormat:@"%02ld:%02ld-%02ld:%02ld",start_hour,start_minute,end_hour,end_minute];
                
                NSMutableArray *items = [NSMutableArray array];
                RHMePolicyModel *chgTagNewModel = [[RHMePolicyModel alloc]init];
                chgTagNewModel.selectList = chgTagModel.selectList.copy;
                chgTagNewModel.key     = chgTagModel.key;
                chgTagNewModel.format  = chgTagModel.format;
                chgTagNewModel.type    = chgTagModel.type;
                chgTagNewModel.regAddr = chgTagModel.regAddr;
                chgTagNewModel.offset  = chgTagModel.offset;
                chgTagNewModel.num     = chgTagModel.num;
                RHMePolicyModel *socNewModel = [[RHMePolicyModel alloc]init];
                socNewModel.key     = [NSString stringWithFormat:@"%@%d",socModel.key,i+1];
                socNewModel.format  = socModel.format;
                socNewModel.type    = socModel.type;
                socNewModel.regAddr = socModel.regAddr + i;
                socNewModel.offset  = socModel.offset;
                socNewModel.num     = socModel.num;
//                socNewModel.content = [NSString stringWithFormat:@"%u",arc4random_uniform(100)];
                RHMePolicyModel *powerNewModel = [[RHMePolicyModel alloc]init];
                powerNewModel.key     = [NSString stringWithFormat:@"%@%d",powerModel.key,i+1];
                powerNewModel.format  = powerModel.format;
                powerNewModel.type    = powerModel.type;
                powerNewModel.regAddr = powerModel.regAddr + i;
                powerNewModel.offset  = powerModel.offset;
                powerNewModel.num     = powerModel.num;
//                powerNewModel.content = [NSString stringWithFormat:@"%u",arc4random_uniform(3000)];
                
                //赋值参数,如果有
                if (paraDic) {
                    //状态
                    if ([paraDic[@"status"] isEqualToString:@"charge"]) {
                        chgTagNewModel.content = @"1";
                    }else if([paraDic[@"status"] isEqualToString:@"discharge"]){
                        chgTagNewModel.content = @"2";
                    }else{
                        chgTagNewModel.content = @"0";
                    }
                    
                    socNewModel.content = ValidNullDataToString(paraDic[@"soc"], @"0");
                    powerNewModel.content = ValidNullDataToString(paraDic[@"power"],@"0");
                }
                [items addObject:chgTagNewModel];
                [items addObject:socNewModel];
                [items addObject:powerNewModel];
                rowNewModel.items = items.copy;
                [rowArr addObject:rowNewModel];
            }
            sectionModel.rows = rowArr.copy;
        }
    }];
}

#pragma mark ---- 使用模板
-(void)patternAction
{
    kWeakSelf;
    RHMePolicyPatternVC *patternVC = [[RHMePolicyPatternVC alloc]init];
    patternVC.usePatternBlock = ^(RHPatternModel * _Nonnull pattern) {
       
        
        //有多少个策略就显示多少
        [weakSelf createPolicyModelWithCount:pattern.segmentNum pattern:pattern];
        weakSelf.textField.text = [NSString stringWithFormat:@"%ld",pattern.segmentNum];
        [weakSelf.tableView reloadData];
    };
    [self.navigationController pushViewController:patternVC animated:YES];
}

-(void)readData:(NSDictionary*)dic
{
    [self.dataArr enumerateObjectsUsingBlock:^(RHMePolicyModel*  _Nonnull sectionModel, NSUInteger idx, BOOL * _Nonnull stop) {
        [sectionModel readDefult:dic];
    }];
    [self.tableView reloadData];
}


-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 10;
    }

    if (section == 1) {
        return 185 - 55;
    }
    return 60;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
       
        return nil;
    }
  
   
    if (section == 1) {
       
        return self.timeView;
    }
    return nil;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
   
    return 0.0;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
   
    
    return nil;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataArr.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    RHMePolicyModel *sectionModel = self.dataArr[section];
//    if ([sectionModel.type isEqualToString:@"time"]) {
//        return self.timeArr.count;
//    }
    return sectionModel.rows.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    RHMePolicyModel *sectionModel = self.dataArr[indexPath.section];
    RHMePolicyModel *rowModel = sectionModel.rows[indexPath.row];
    if ([rowModel.type isEqualToString:@"date"]) {//系统时间校准
        RHMePolicySystemTimeCell *dateCell = [tableView dequeueReusableCellWithIdentifier:@"RHMePolicySystemTimeCell"];
        dateCell.model = rowModel;
        kWeakSelf;
        //时间选择
        dateCell.selectAction = ^(RHMePolicyModel * _Nonnull model) {
            [weakSelf dateAction:model];
        };
        //时间设置
        dateCell.setAction = ^(RHMePolicyModel * _Nonnull model) {
            [weakSelf setDateAction:model];
        };
        //时间读取
        dateCell.readAction = ^(RHMePolicyModel * _Nonnull model) {
          
        };
        return dateCell;
    }
    else  if ([rowModel.type isEqualToString:@"time"]) {//充放电时段设置
        RHMePolicyModel *timeRowModel = rowModel;
        RHMePolicyTimeRangeCell *settingCell = [tableView dequeueReusableCellWithIdentifier:@"RHMePolicyTimeRangeCell"];
        timeRowModel.rowTitle = [NSString stringWithFormat:@"%@ %ld",@"时段".rh_localized,indexPath.row+1];
        settingCell.model = timeRowModel;
        kWeakSelf;
        settingCell.selectAction = ^(RHMePolicyModel * _Nonnull model) {
            [weakSelf editChargeDischargeInfo:model index:indexPath.row+1];
        };
        if(indexPath.row == sectionModel.rows.count-1){
            [settingCell.bgView setBottomBorder];
        }else{
            [settingCell.bgView setMiddleBorder];
        }
        return settingCell;
    }
    return [UITableViewCell new];
}

-(UIView*)timeView
{
    if (!_timeView) {
        _timeView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 125)];
        _timeView.backgroundColor = kCOLOR_HEX(@"#F0F5FF");
        
        kWeakSelf;
        UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(15, 15, kUI_WINDOW_W-30, 45)];
        bgView.backgroundColor = UIColor.whiteColor;
        [bgView roundBorder:8 width:1 color:kBorderColor RectCorners:QMUIViewBorderPositionTop|QMUIViewBorderPositionLeft|QMUIViewBorderPositionRight];
        bgView.layer.qmui_maskedCorners = QMUILayerMinXMinYCorner|QMUILayerMaxXMinYCorner;
        [_timeView addSubview:bgView];
        [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(15);
            make.right.mas_offset(-15);
            make.top.mas_offset(15);
            make.bottom.mas_offset(0);
        }];
        
        QMUILabel *titleLab = [QMUILabel labelWithText:@"时段设置".rh_localized font:kSYSTEMFONT(16) textColor:kCOLOR_HEX(@"#171A1D")];
        titleLab.textAlignment = NSTextAlignmentLeft;
        titleLab.numberOfLines = 0;
        [bgView addSubview:titleLab];
        [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(15);
            make.top.mas_offset(15);
            make.right.mas_offset(-15);
        }];
        
        UIView *policyView = kView;
        policyView.backgroundColor = UIColor.clearColor;
        [bgView addSubview:policyView];
        [policyView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_offset(0);
            make.top.equalTo(titleLab.mas_bottom).offset(15);
            make.height.offset(40);
        }];
        
        QMUILabel *policyTitleLab = [QMUILabel labelWithFont:kSYSTEMFONT(14) textColor:kCOLOR_HEX(@"#474B53") textAligment:NSTextAlignmentLeft];
        policyTitleLab.text = @"策略数量".rh_localized;
        [policyView addSubview:policyTitleLab];
        [policyTitleLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(15);
            make.centerY.mas_offset(0);
        }];
        
        QMUIButton *addBtn = [QMUIButton buttonWithTitle:@"+" titleColor:kCOLOR_HEX_A(@"#171A1D",0.3) titleFont:kSYSTEMFONT(20)];
        [addBtn rounded:8 width:1 color:kCOLOR_HEX(@"#E3E6ED")];
        [policyView addSubview:addBtn];
        [addBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.height.offset(34);
            make.right.mas_offset(-15);
            make.centerY.mas_offset(0);
        }];
        
        QMUITextField *textField = [[QMUITextField alloc]init];
        textField.textColor = kCOLOR_HEX(@"#303133");
        textField.font = kSYSTEMFONT(14);
        textField.textAlignment = NSTextAlignmentCenter;
        [textField rounded:8 width:1 color:kCOLOR_HEX(@"#E3E6ED")];
        [policyView addSubview:textField];
        self.textField = textField;
        [textField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.offset(80);
            make.height.offset(34);
            make.centerY.mas_offset(0);
            make.right.equalTo(addBtn.mas_left).offset(-10);
        }];
        
        QMUIButton *reduceBtn = [QMUIButton buttonWithTitle:@"-" titleColor:kCOLOR_HEX_A(@"#171A1D",0.3) titleFont:kSYSTEMFONT(16)];
        [reduceBtn rounded:8 width:1 color:kCOLOR_HEX(@"#E3E6ED")];
        [policyView addSubview:reduceBtn];
        [reduceBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.height.offset(34);
            make.right.equalTo(textField.mas_left).offset(-10);
            make.centerY.mas_offset(0);
        }];
        
        UIView *optionView = [[UIView alloc]init];
        optionView.backgroundColor = UIColor.whiteColor;
        [bgView addSubview:optionView];
        [optionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_offset(0);
            make.top.equalTo(titleLab.mas_bottom).offset(15);
        }];
        
        [[addBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
            NSInteger textValue = [textField.text integerValue];
            if (textValue < 24) {
                textField.text = [NSString stringWithFormat:@"%ld",textValue+1];
                [weakSelf addRowCount:1];
            }
            
        }];
        
        [[reduceBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
            NSInteger textValue = [textField.text integerValue];
            if (textValue > 1) {
                textField.text = [NSString stringWithFormat:@"%ld",textValue-1];
                [weakSelf reduceRowCount:1];
            }
            
        }];
        //去掉策略数据
        policyView.hidden = YES;
        
        __block QMUIButton *lastItem;
        __block CGFloat btnWidth = (kUI_WINDOW_W - 30-(15*5))/4;
        NSArray *timeArr = @[@"4",@"6",@"12",@"24"];
        textField.text = [timeArr firstObject];
        [timeArr enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            QMUIButton *btn = [[QMUIButton alloc]init];
            [btn setTitle:obj forState:UIControlStateNormal];
            btn.titleLabel.font = kSYSTEMFONT(14);
            [btn setTitleColor:[UIColor colorWithHexString:@"3F4443" alpha:0.8] forState:UIControlStateNormal];
            btn.backgroundColor = kCOLOR_HEX(@"F6F8FA");
            btn.layer.cornerRadius = 8;
            btn.userInteractionEnabled = YES;
            [btn setBackgroundColor:kCOLOR_HEX(@"FFFFFF")];
            [optionView addSubview:btn];
            btn.tag = [obj integerValue];
            [btn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.width.offset(btnWidth);
                make.height.offset(36);
                if(lastItem){
                    if (idx%4==0) {//换行
                        make.left.mas_offset(15);
                        make.top.equalTo(lastItem.mas_bottom).offset(15);
                    }else{
                        make.left.equalTo(lastItem.mas_right).offset(15);
                        make.top.equalTo(lastItem);
                    }
                    
                }else{
                    make.left.mas_offset(15);
                    make.top.mas_offset(0);
                }
            }];
         
            lastItem = btn;
            kWeakSelf;
            [[btn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
                weakSelf.timeIndex = idx;
                textField.text = obj;
                [weakSelf changeRowCount:[obj integerValue]];
            }];
            
            [RACObserve(self, timeIndex) subscribeNext:^(id  _Nullable x) {
                if([x integerValue] == idx){
                    [btn setTitleColor:[UIColor colorWithHexString:@"ffffff" alpha:1] forState:UIControlStateNormal];
                    [btn setBackgroundColor:CMainColorGreen];
                    btn.layer.borderWidth = 0;
                }else{
                    [btn setTitleColor:[UIColor colorWithHexString:@"3F4443" alpha:0.6] forState:UIControlStateNormal];
                    [btn setBackgroundColor:kCOLOR_HEX(@"#F3F7FF")];
                    btn.layer.borderColor = kBorderColor.CGColor;
                    btn.layer.borderWidth = 1;
                }
            }];
            [textField.rac_textSignal subscribeNext:^(NSString * _Nullable x) {
                if([obj isEqualToString:x]){
                    [btn setTitleColor:[UIColor colorWithHexString:@"ffffff" alpha:1] forState:UIControlStateNormal];
                    [btn setBackgroundColor:CMainColorGreen];
                    btn.layer.borderWidth = 0;
                }else{
                    [btn setTitleColor:[UIColor colorWithHexString:@"3F4443" alpha:0.6] forState:UIControlStateNormal];
                    [btn setBackgroundColor:kCOLOR_HEX(@"#F3F7FF")];
                    btn.layer.borderColor = kBorderColor.CGColor;
                    btn.layer.borderWidth = 1;
                }
                //最多24个时间段
                if ([x integerValue]>24) {
                    textField.text = @"24";
                }
                //最少一个时间段
                if ([x integerValue]<0) {
                    textField.text = @"1";
                }
            }];
       
        }];
        [lastItem mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_offset(0);
        }];
    }
    return _timeView;
    
    
}

//点击了标签个数
-(void)changeRowCount:(NSInteger)changeCount
{
    [self createPolicyModelWithCount:changeCount pattern:nil];
//    __block NSInteger rowCount;
//    [self.dataArr enumerateObjectsUsingBlock:^(RHMePolicyModel*  _Nonnull sectionModel, NSUInteger idx, BOOL * _Nonnull stop) {
//        if ([sectionModel.type isEqualToString:@"time"]) {
//            rowCount = sectionModel.rows.count;
//        }
//    }];
//    if (rowCount>changeCount) {
//        [self reduceRowCount:rowCount - changeCount];
//    }
//    if (rowCount<changeCount) {
//        [self addRowCount:changeCount - rowCount];
//    }
    [self.tableView reloadData];
}

#pragma mark ---- 增加时间段
-(void)addRowCount:(NSInteger)count
{
    [self.dataArr enumerateObjectsUsingBlock:^(RHMePolicyModel*  _Nonnull sectionModel, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([sectionModel.type isEqualToString:@"time"]) {
            NSMutableArray *rowArr = [NSMutableArray arrayWithArray:sectionModel.rows];
            RHMePolicyModel *rowModel = [sectionModel.rows firstObject];
            RHMePolicyModel *chgTagModel = [rowModel.items safeObjectAtIndex:0];
            RHMePolicyModel *socModel = [rowModel.items safeObjectAtIndex:1];
            RHMePolicyModel *powerModel = [rowModel.items safeObjectAtIndex:2];
            NSInteger time_index = sectionModel.rows.count;
            for (NSInteger i = 0; i <count; i++) {
                RHMePolicyModel *rowNewModel = [[RHMePolicyModel alloc]init];
                rowNewModel.type = rowModel.type;
                rowNewModel.comment = [NSString stringWithFormat:@"%02ld:00-%02ld:00",time_index+i,time_index+i+1];
                
                NSMutableArray *items = [NSMutableArray array];
                RHMePolicyModel *chgTagNewModel = [[RHMePolicyModel alloc]init];
                chgTagNewModel.selectList = chgTagModel.selectList.copy;
                chgTagNewModel.key     = chgTagModel.key;
                chgTagNewModel.format  = chgTagModel.format;
                chgTagNewModel.type    = chgTagModel.type;
                chgTagNewModel.regAddr = chgTagModel.regAddr;
                chgTagNewModel.offset  = chgTagModel.offset;
                chgTagNewModel.num     = chgTagModel.num;
                RHMePolicyModel *socNewModel = [[RHMePolicyModel alloc]init];
                socNewModel.key     = [NSString stringWithFormat:@"%@%ld",socModel.key,i+1];
                socNewModel.format  = socModel.format;
                socNewModel.type    = socModel.type;
                socNewModel.regAddr = socModel.regAddr + i;
                socNewModel.offset  = socModel.offset;
                socNewModel.num     = socModel.num;
//                socNewModel.content = [NSString stringWithFormat:@"%u",arc4random_uniform(100)];
                RHMePolicyModel *powerNewModel = [[RHMePolicyModel alloc]init];
                powerNewModel.key     = [NSString stringWithFormat:@"%@%d",powerModel.key,i+1];
                powerNewModel.format  = powerModel.format;
                powerNewModel.type    = powerModel.type;
                powerNewModel.regAddr = powerModel.regAddr + i;
                powerNewModel.offset  = powerModel.offset;
                powerNewModel.num     = powerModel.num;
//                powerNewModel.content = [NSString stringWithFormat:@"%u",arc4random_uniform(3000)];
                [items addObject:chgTagNewModel];
                [items addObject:socNewModel];
                [items addObject:powerNewModel];
                rowNewModel.items = items.copy;
                [rowArr addObject:rowNewModel];
            }
            sectionModel.rows = rowArr.copy;
        }
    }];
    [self.tableView reloadData];
}

#pragma mark ---- 删除时间段
-(void)reduceRowCount:(NSInteger)count
{
    [self.dataArr enumerateObjectsUsingBlock:^(RHMePolicyModel*  _Nonnull sectionModel, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([sectionModel.type isEqualToString:@"time"]) {
            NSMutableArray *rowArr = [NSMutableArray arrayWithArray:sectionModel.rows];
            
            for (NSInteger i = 0; i <count; i++) {
                
                [rowArr removeLastObject];
            }
            sectionModel.rows = rowArr.copy;
        }
    }];
    [self.tableView reloadData];
}


#pragma mark -------- 充放电时间段选择
-(void)editChargeDischargeInfo:(RHMePolicyModel*)model index:(NSInteger)index
{
    kWeakSelf;
    RHMePolicyEditTimeVC *editVC = [[RHMePolicyEditTimeVC alloc]init];
    editVC.index = index;
    editVC.model = model;
    editVC.sureBlock = ^{
        [weakSelf.tableView reloadData];
    };
    [self.navigationController pushViewController:editVC animated:YES];
}

#pragma mark -------- 选择时间
- (void)dateAction:(RHMePolicyModel *)settingModel  {
    
    WSDatePickerView *datePickerV = [[WSDatePickerView alloc] initWithDateStyle:DateStyleShowYearMonthDayHourMinuteSecond CompleteBlock:^(NSDate *selectDate) {
        NSString *dateFormatStr = @"yyyy/MM/dd HH:mm:ss";
        NSString *currentDate = [selectDate stringWithFormat: dateFormatStr];
        settingModel.content = currentDate;
        [self.tableView reloadData];
    }];
    datePickerV.dateLabelColor = FontColor(@"#3ECE80");//年-月 颜色
    datePickerV.datePickerColor = UIColorBlack;//滚轮日期颜色
    datePickerV.doneButtonColor = UIColor.blackColor;//确定按钮的颜色
    [datePickerV show];
}

#pragma mark ------ 选择
-(void)selectAction:(RHMePolicyModel*)model
{
    kWeakSelf;
    SettingOptionController *vc = [[SettingOptionController alloc] initWithData:model.selectList];
    [[RHWindowTipManage shareWindowTipManage] showWithController:vc];
    
    vc.curTextValue = [model.content integerValue];
   
    vc.selectBlock = ^(NSInteger index) {
        DevSettingOptionModel *select_model = model.selectList[index];
        model.enumText = select_model.text;//存要显示的内容
        model.content = [NSString stringWithFormat:@"%ld",select_model.textValue];//存下标
        [weakSelf.tableView reloadData];
    };
}


#pragma mark -------- 新增策略配置

-(void)addAction
{
    kWeakSelf;
    RHMePolicyAddTipsView *addView = [[RHMePolicyAddTipsView alloc]init];
    [addView showWithTitle:@"添加策略模板".rh_localized detail:@"策略模板名称".rh_localized];
    addView.finishBlock = ^(NSString * _Nonnull patternName) {
        [weakSelf addPattern:patternName];
    };
}

-(void)addPattern:(NSString *)patternName
{
    
    NSMutableArray *paraArray = [NSMutableArray array];
  
    [self.dataArr enumerateObjectsUsingBlock:^(RHMePolicyModel*  _Nonnull sectionModel, NSUInteger idx, BOOL * _Nonnull stop) {
        
        
        [sectionModel.rows enumerateObjectsUsingBlock:^(RHMePolicyModel * _Nonnull rowModel, NSUInteger idx, BOOL * _Nonnull stop) {
            //保存参数的字典
            NSMutableDictionary *paraDic = [NSMutableDictionary dictionary];
            
            //时间段设置
            if ([rowModel.type isEqualToString:@"time"]) {
                NSArray *timeArr = [rowModel.comment componentsSeparatedByString:@"-"];
                [paraDic setObject:@(idx+1)  forKey:@"index"];
                [paraDic setObject:[timeArr firstObject]  forKey:@"startTime"];
                [paraDic setObject:[timeArr lastObject]  forKey:@"endTime"];
                RHMePolicyModel *chgStateModel = [rowModel.items firstObject];//充放电状态
                [rowModel.items enumerateObjectsUsingBlock:^(RHMePolicyModel * _Nonnull itemModel, NSUInteger idx, BOOL * _Nonnull stop) {
//                    if (itemModel.content.length == 0||itemModel.key.length == 0) {//充放电字段不提交
//                        return;
//                    }
                    NSMutableDictionary *itemDic = [NSMutableDictionary dictionary];
                    [itemDic setObject:itemModel.format forKey:@"dataType"];
                    [itemDic setObject:itemModel.key forKey:@"paramName"];
                    [itemDic setObject:ValidNullDataToString(itemModel.content, @"0") forKey:@"value"];
                    [itemDic setObject:@(itemModel.regAddr) forKey:@"regAddr"];
                    [itemDic setObject:@(itemModel.num) forKey:@"num"];
                    [itemDic setObject:@(itemModel.offset) forKey:@"offset"];
                    if (idx == 1) {
                        [paraDic setObject:@([itemModel.content integerValue]) forKey:@"soc"];
                    }
                    //功率值要根所充放电状态来发送正负值
                    if (idx == 2) {//功率
                        NSString *power = @"0";
                        NSString *status = @"standby";
                        if ([chgStateModel.content integerValue] == 1) {//充电发负数
                            if (![itemModel.content containsString:@"-"]) {
                                NSString *value = [NSString stringWithFormat:@"-%@",itemModel.content];
                                [itemDic setObject:value forKey:@"value"];
                                power = value;
                                status = @"charge";
                            }
                        }
                        if ([chgStateModel.content integerValue] == 2) {//放电发正数
                            NSString *value = [itemModel.content stringByReplacingOccurrencesOfString:@"-" withString:@""];
                            [itemDic setObject:value forKey:@"value"];
                            power = value;
                            status = @"discharge";
                        }
                        [paraDic setObject:@([itemModel.content integerValue]) forKey:@"power"];
                        [paraDic setObject:status forKey:@"status"];
                    }
                    
                    //时间
                    if ([itemModel.type isEqualToString:@"date"]) {
                        NSString *content = [itemModel.content stringByReplacingOccurrencesOfString:@":" withString:@""];
                        [itemDic setObject:ValidNullData(content) forKey:@"value"];
                    }
                    [self.paraSectionArr addObject:itemDic];
                }];
            }
            if (paraDic.allKeys.count>0) {
                [paraArray addObject:paraDic];
            }
           
        }];
        
    }];
    
   
    NSString *paraStr = [paraArray yy_modelToJSONString];//转成字符串保存
    NSMutableDictionary *savePara = @{
        @"strategyName":patternName,
        @"segmentNum":@([self.textField.text integerValue]),
        @"configJson":paraStr
    }.mutableCopy;
    //如果有地址
    if (self.addressDic) {
        [savePara addEntriesFromDictionary:self.addressDic];
    }
    
    [QMUITips showLoading:@"" inView:kApplication.keyWindow];

    [BaseModel startWithCompletionAPIKey:H_addPolicyConfig argument:savePara requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if (resultModel.code == 200) {

            [QMUITips showSucceed:@"成功".rh_localized inView:self.view hideAfterDelay:1];
           
        }
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
      
    }];
}


#pragma mark ------ 策略下发
-(void)sendAction
{
    [self.paraSectionArr removeAllObjects];
   
    
    //---------提取出参数,存的是每行的soc,power字典,正负数处理,发送时直接使用
    NSMutableArray *paraArrM = [NSMutableArray array];
    
    [self.dataArr enumerateObjectsUsingBlock:^(RHMePolicyModel*  _Nonnull sectionModel, NSUInteger idx, BOOL * _Nonnull stop) {
       
        [sectionModel.rows enumerateObjectsUsingBlock:^(RHMePolicyModel * _Nonnull rowModel, NSUInteger idx, BOOL * _Nonnull stop) {
        
            if ([rowModel.type isEqualToString:@"time"]) {
                NSMutableDictionary *dicM = [NSMutableDictionary dictionary];
                NSArray *timeArr = [rowModel.comment componentsSeparatedByString:@"-"];
                [dicM setObject:@(idx+1)  forKey:@"index"];
                [dicM setObject:[timeArr firstObject]  forKey:@"startTime"];
                [dicM setObject:[timeArr lastObject]  forKey:@"endTime"];
                
                RHMePolicyModel *chgStateModel = [rowModel.items firstObject];//充放电状态
                [rowModel.items enumerateObjectsUsingBlock:^(RHMePolicyModel * _Nonnull itemModel, NSUInteger idx, BOOL * _Nonnull stop) {
                    
                    NSMutableDictionary *itemDic = [NSMutableDictionary dictionary];
                    [itemDic setObject:itemModel.format forKey:@"dataType"];
                    [itemDic setObject:itemModel.key forKey:@"paramName"];
                    [itemDic setObject:ValidNullDataToString(itemModel.content, @"0") forKey:@"value"];
                    [itemDic setObject:@(itemModel.regAddr) forKey:@"regAddr"];
                    [itemDic setObject:@(itemModel.num) forKey:@"num"];
                    [itemDic setObject:@(itemModel.offset) forKey:@"offset"];
                    if(idx == 0){//充放电状态
                        
                    }
                    
                    if (idx==1) {//soc
                        [dicM setObject:ValidNullDataToString(itemModel.content, @"0") forKey:@"soc"];
                    }
                    //功率值要根所充放电状态来发送正负值
                    if (idx == 2) {//功率
                        NSString *value = @"0";
                        NSString *status = @"standby";//充放状态
                        if ([chgStateModel.content integerValue] == 1) {//充电发负数
                            if (![itemModel.content containsString:@"-"]) {
                                value = [NSString stringWithFormat:@"-%@",itemModel.content];
                                [itemDic setObject:value forKey:@"value"];
                                status = @"charge";
                            }
                        }
                        if ([chgStateModel.content integerValue] == 2) {//放电发正数
                            value = [itemModel.content stringByReplacingOccurrencesOfString:@"-" withString:@""];
                            [itemDic setObject:value forKey:@"value"];
                            status = @"discharge";
                        }
                        [dicM setObject:value forKey:@"power"];
                        [dicM setObject:status forKey:@"status"];
                    }
                    
                    //时间
                    if ([itemModel.type isEqualToString:@"date"]) {
                        NSString *content = [itemModel.content stringByReplacingOccurrencesOfString:@":" withString:@""];
                        [itemDic setObject:ValidNullData(content) forKey:@"value"];
                    }

                }];
                [paraArrM addObject:dicM];
            }
            
        }];
        
    }];
    
    
    if(paraArrM.count == 0)return;
    //组装要发送的参数
    [self create233SendParaModel:paraArrM.copy];
    
   
    
    NSMutableDictionary *requestPara = [NSMutableDictionary dictionary];
    
    //分组id
    [requestPara setObject:@(self.plantId) forKey:@"plantId"];
    
    //参数的body
    NSMutableDictionary *bodyDic = [NSMutableDictionary dictionary];
    NSMutableArray *paraListArr = [NSMutableArray array];
    
    //全部参数一次性给到后台 , 不需要填端点sn参数,因为获取不到
    [paraListArr addObjectsFromArray:self.paraSectionArr];

    if (paraListArr.count == 0) {
        return;
    }
    [bodyDic setObject:paraListArr forKey:@"commandParamList"];
    [requestPara setValue:bodyDic forKey:@"protocolBody"];
    
    //下发的同时保存配置参数, 把负数改成正数
    [paraArrM enumerateObjectsUsingBlock:^(NSMutableDictionary*  _Nonnull dicM, NSUInteger idx, BOOL * _Nonnull stop) {
        if([dicM[@"power"] containsString:@"-"]){
            [dicM setObject:[dicM[@"power"] stringByReplacingOccurrencesOfString:@"-" withString:@""] forKey:@"power"];
        }
    }];
    NSString *paraConfigStr = [paraArrM yy_modelToJSONString];//转成字符串保存
    if(paraConfigStr){
        [requestPara setObject:paraConfigStr forKey:@"configJson"];
    }
    
    //参数的头部
    NSString *randomStr = [NSString generateRandomLetter:15];
    NSTimeInterval interval = [[NSDate date] timeIntervalSince1970]*1000;
    NSDictionary *headContent = @{
        @"cmdId": randomStr,
        
        @"paramCount":@(paraListArr.count),
      
        @"messageType": @(1),//下行
        @"namespace": @"ParamSetSingle",
        @"payloadVersion": @(1),
        @"timestamp": @((NSInteger)interval)
      };
    [requestPara setValue:headContent forKey:@"protocolHead"];
    
    [QMUITips showLoading:@"" inView:kApplication.keyWindow];

    [BaseModel startWithCompletionAPIKey:H_plantPolicySend argument:requestPara requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if (resultModel.code == 200) {

            [QMUITips showSucceed:@"完成".rh_localized inView:self.view hideAfterDelay:1];
            
        }
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
      
    }];
}

#pragma mark ----- 创建要发送的参数模型
-(NSArray*)create233SendParaModel:(NSArray*)paraArrM
{
    NSDictionary *modeDic = @{
        @"paramName": @"EMU_CutPeaks_Fillvalleys",
        @"value": @"1",
        @"num": @(16),
        @"offset": @(0),
        @"dataType": @"int",
        @"regAddr": @(1699)
    };
    [self.paraSectionArr addObject:modeDic];//工作模式
    
    NSArray *arr = [SYChartTool loadJsonFileWithName:@"me_policy_config"];
    //取时间段设置
    NSArray *dataArr = [NSArray yy_modelArrayWithClass:[RHMePolicyModel class] json:arr];
    
    NSMutableArray *rowArr = [NSMutableArray array];
    [dataArr enumerateObjectsUsingBlock:^(RHMePolicyModel*  _Nonnull sectionModel, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([sectionModel.type isEqualToString:@"time"]) {
            RHMePolicyModel *rowModel = [sectionModel.rows firstObject];
            RHMePolicyModel *chgTagModel = [rowModel.items safeObjectAtIndex:0];
            RHMePolicyModel *socModel = [rowModel.items safeObjectAtIndex:1];
            RHMePolicyModel *powerModel = [rowModel.items safeObjectAtIndex:2];
            
            for (int i = 0; i <24; i++) {

                RHMePolicyModel *rowNewModel = [[RHMePolicyModel alloc]init];
                rowNewModel.type = rowModel.type;
                rowNewModel.comment = [NSString stringWithFormat:@"%02d:00-%02d:00",i,i+1];
                
                NSMutableArray *items = [NSMutableArray array];
                RHMePolicyModel *chgTagNewModel = [[RHMePolicyModel alloc]init];
                chgTagNewModel.selectList = chgTagModel.selectList.copy;
                chgTagNewModel.key     = chgTagModel.key;
                chgTagNewModel.format  = chgTagModel.format;
                chgTagNewModel.type    = chgTagModel.type;
                chgTagNewModel.regAddr = chgTagModel.regAddr;
                chgTagNewModel.offset  = chgTagModel.offset;
                chgTagNewModel.num     = chgTagModel.num;
                RHMePolicyModel *socNewModel = [[RHMePolicyModel alloc]init];
                socNewModel.key     = [NSString stringWithFormat:@"%@%d",socModel.key,i+1];
                socNewModel.format  = socModel.format;
                socNewModel.type    = socModel.type;
                socNewModel.regAddr = socModel.regAddr + i;
                socNewModel.offset  = socModel.offset;
                socNewModel.num     = socModel.num;
//                socNewModel.content = [NSString stringWithFormat:@"%u",arc4random_uniform(100)];
                RHMePolicyModel *powerNewModel = [[RHMePolicyModel alloc]init];
                powerNewModel.key     = [NSString stringWithFormat:@"%@%d",powerModel.key,i+1];
                powerNewModel.format  = powerModel.format;
                powerNewModel.type    = powerModel.type;
                powerNewModel.regAddr = powerModel.regAddr + i;
                powerNewModel.offset  = powerModel.offset;
                powerNewModel.num     = powerModel.num;
//                powerNewModel.content = [NSString stringWithFormat:@"%u",arc4random_uniform(3000)];
                
                [items addObject:chgTagNewModel];
                [items addObject:socNewModel];
                [items addObject:powerNewModel];
                rowNewModel.items = items.copy;
                [rowArr addObject:rowNewModel];
            }
            sectionModel.rows = rowArr.copy;
        }
    }];
    
   
    [dataArr enumerateObjectsUsingBlock:^(RHMePolicyModel*  _Nonnull sectionModel, NSUInteger idx, BOOL * _Nonnull stop) {
       
        [sectionModel.rows enumerateObjectsUsingBlock:^(RHMePolicyModel * _Nonnull rowModel, NSUInteger rowIdx, BOOL * _Nonnull stop) {
            NSDictionary *dataDic = [paraArrM safeObjectAtIndex:rowIdx/ (24/paraArrM.count)];
            //只处理时间段
            if ([rowModel.type isEqualToString:@"time"]) {
                
                [rowModel.items enumerateObjectsUsingBlock:^(RHMePolicyModel * _Nonnull itemModel, NSUInteger idx, BOOL * _Nonnull stop) {
                    
                    if([itemModel.type isEqualToString:@"select"])return;//充放电使能
                    
                    NSMutableDictionary *itemDic = [NSMutableDictionary dictionary];
                    [itemDic setObject:itemModel.format forKey:@"dataType"];
                    [itemDic setObject:itemModel.key forKey:@"paramName"];
                    [itemDic setObject:ValidNullDataToString(itemModel.content, @"0") forKey:@"value"];
                    [itemDic setObject:@(itemModel.regAddr) forKey:@"regAddr"];
                    [itemDic setObject:@(itemModel.num) forKey:@"num"];
                    [itemDic setObject:@(itemModel.offset) forKey:@"offset"];
                   
                    if (idx == 1) {//soc
                        [itemDic setObject:dataDic[@"soc"] forKey:@"value"];
                    }
                    //功率值要根所充放电状态来发送正负值,已在提取时做了处理
                    if (idx == 2) {//功率
                        [itemDic setObject:dataDic[@"power"] forKey:@"value"];
                    }
                    
                    //时间
                    if ([itemModel.type isEqualToString:@"date"]) {
                        NSString *content = [itemModel.content stringByReplacingOccurrencesOfString:@":" withString:@""];
                        [itemDic setObject:ValidNullData(content) forKey:@"value"];
                    }
                    [self.paraSectionArr addObject:itemDic];
                }];
        
            }
            
        }];
        
    }];
    return  dataArr;
}

#pragma mark ------ 时间校准 密码校验
-(void)setDateAction:(RHMePolicyModel*)model
{
    if (model.content.length == 0) {
        return;
    }
    //    PasswordVerifyController *vc = [[PasswordVerifyController alloc] init];
    //    [[RHWindowTipManage shareWindowTipManage] showWithController:vc];
    //
    //    kWeakSelf;
    //    vc.callBackBlock = ^(NSString * _Nonnull password) {
    //                NSDictionary *dic = [RHTools getAccountInfo];
    //                if ([SafeStr(dic[@"password"]) isEqualToString:password]) {
    //                    [weakSelf systemTimeVerity:model];
    //                }else{
    //                    [QMUITips showInfo:@"密码错误".rh_localized];
    //                }
    //    };
        
    [self systemTimeVerity:model];
}

#pragma mark ------ 时间校准
-(void)systemTimeVerity:(RHMePolicyModel*)model
{
    NSMutableDictionary *requestPara = [NSMutableDictionary dictionary];
    
    //电站id
    [requestPara setObject:@(self.plantId) forKey:@"plantId"];
  
    
    //参数的body
    NSMutableDictionary *bodyDic = [NSMutableDictionary dictionary];
    NSMutableArray *paraListArr = [NSMutableArray array];
    
    if (model.content.length>0) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        formatter.dateFormat = @"yyyy/MM/dd HH:mm:ss";
        formatter.timeZone = [NSTimeZone localTimeZone];
        NSDate *date = [formatter dateFromString:model.content];
        [self processTimeParams:paraListArr date:date];
    }

    if (paraListArr.count == 0) {
        return;
    }
    [bodyDic setObject:paraListArr forKey:@"commandParamList"];
    [requestPara setValue:bodyDic forKey:@"protocolBody"];
    
    //参数的头部
    NSString *randomStr = [NSString generateRandomLetter:15];
    NSTimeInterval interval = [[NSDate date] timeIntervalSince1970]*1000;
    NSDictionary *headContent = @{
        @"cmdId": randomStr,
        @"paramCount":@(paraListArr.count),
        @"messageType": @(1),//下行
        @"namespace": @"ParamSetSingle",
        @"payloadVersion": @(1),
        @"timestamp": @((NSInteger)interval)
      };
    [requestPara setValue:headContent forKey:@"protocolHead"];
    
    [QMUITips showLoading:@"设置中...".rh_localized inView:kApplication.keyWindow];

    [BaseModel startWithCompletionAPIKey:H_plantPolicySend argument:requestPara requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if (resultModel.code == 200) {
            [QMUITips showSucceed:@"设置完成".rh_localized inView:self.view hideAfterDelay:1];
            
            
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
    
    }];
    
}

#pragma mark -------处理233时间校准格式
-(void)processTimeParams:(NSMutableArray*)paramList date:(NSDate*)date
{
    NSArray *keys = @[@"Emu_ctrlTimYear",@"Emu_ctrlTimMon",@"Emu_ctrlTimDay",@"Emu_ctrlTimHur",@"Emu_ctrlTimMin",@"Emu_ctrlTimSec"];
    NSArray *regAdrrs = @[@(5100),@(5100),@(5101),@(5101),@(5102),@(5102)];
    NSArray *offsets = @[@(8),@(0),@(8),@(0),@(8),@(0)];
    NSArray *value = @[@(date.year),@(date.month),@(date.day),@(date.hour),@(date.minute),@(date.second)];
    [keys enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSMutableDictionary *timeDic = [NSMutableDictionary dictionary];
        NSString *valueStr = [NSString stringWithFormat:@"%02ld",[value[idx] integerValue]];
        [timeDic setObject:@"int" forKey:@"dataType"];
        [timeDic setObject:keys[idx] forKey:@"paramName"];
        [timeDic setObject:valueStr forKey:@"value"];
        [timeDic setObject:regAdrrs[idx] forKey:@"regAddr"];//5100-5102
        [timeDic setObject:@(8) forKey:@"num"];
        [timeDic setObject:offsets[idx] forKey:@"offset"];
        [paramList addObject:timeDic];
    }];
   
}



-(UIView*)footerView{
    kWeakSelf;
    UIView *footer = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 15+50+15+50+(kSafe_bottom>0?kSafe_bottom:15))];
    
    QMUIButton *saveBtn = [QMUIButton buttonWithTitle:@"添加到模板".rh_localized titleColor:UIColor.whiteColor titleFont:kBOLDSYSTEMFONT(20)];
    [saveBtn setBackgroundColor:CMainColorGreen];
    [saveBtn setCornerRadius:8];
    [footer addSubview:saveBtn];
    [saveBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_offset(15);
        make.left.mas_offset(15);
        make.height.offset(50);
        make.right.mas_offset(-15);
    }];
    
    QMUIButton *sendCmdBtn = [QMUIButton buttonWithTitle:@"策略下发".rh_localized titleColor:CMainColorGreen titleFont:kBOLDSYSTEMFONT(18)];
    [sendCmdBtn setCornerRadius:8];
    [sendCmdBtn setQmui_borderColor:CMainColorGreen];
    [sendCmdBtn setQmui_borderWidth:1];
    [sendCmdBtn setQmui_borderPosition:QMUIViewBorderPositionTop|QMUIViewBorderPositionLeft|QMUIViewBorderPositionRight|QMUIViewBorderPositionBottom ];
    [sendCmdBtn setBackgroundColor:kCOLOR_HEX_A(@"#05C79D", 0.1)];
    
    [footer addSubview:sendCmdBtn];
    [sendCmdBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.top.equalTo(saveBtn.mas_bottom).offset(15);
        make.bottom.mas_offset(kSafe_bottom>0?-kSafe_bottom:-15);
    }];
    
    [[saveBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf addAction];
    }];
    
    [[sendCmdBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf sendAction];
      
    }];
    return footer;
}



@end
